package org.proddevplm.business.product;

import java.util.List;
import java.util.Map;

import org.proddevplm.business.api.AController;
import org.proddevplm.business.product.constants.ProductConstants;
import org.proddevplm.constants.ControllerConstants;
import org.proddevplm.dao.data.Product;

public class ProductController extends AController{

	@Override
	public Object execute(int command, Object data) {
		
		Map<String, Object> productMap = (Map<String, Object>) data;
		int productId;
		
		switch (command){
		case ProductConstants.ADD_PRODUCT:
					
			try{
				Product product = new Product();
				int projectId = (Integer) getSession().getAttribute("projectId");
				
				product.setName((String)productMap.get("productName"));
				product.setDescription((String)productMap.get("productDescription"));
				product.setLeader((String)productMap.get("teamLeader"));
				product.setStartDate((String)productMap.get("productStartDate"));
				product.setEndDate((String)productMap.get("productEndDate"));
				
				product.setProject_id(projectId);
				
				getDaoManager().getProductManager().addProduct(product);
				
				List<Product> productsByProjectId = getDaoManager().getProductManager().getProductsByProjectId(projectId);
				putOnSession("products", productsByProjectId);
				
				productId = product.getId();
				putOnSession("productId", productId);
				
			}catch (Exception e) {
            	e.printStackTrace();
			}
			putOnState(ControllerConstants.NEXT_PAGE, "content/project/projectPage.jsp");
			putOnSession("currentTab", "tab2");
			
			break;
			
		case ProductConstants.OPEN_PRODUCT:
           
            int projectId = (Integer)getSession().getAttribute("projectId");
            
            //DB Call 1
            List<Product> productsByProjectId = getDaoManager().getProductManager().getProductsByProjectId(projectId);
            putOnSession("products", productsByProjectId);
            
            if(productMap.get("productId") != null){
            	productId = Integer.valueOf((String)productMap.get("productId"));
            	putOnSession("productId", productId);
            
            	//DB Call 2
            	Product currentProduct = getDaoManager().getProductManager().getProductById(productId);

	            //DBCall 1 si DBCall 2 este un bad practice. Pentru ca mergi de 2 ori la DB
	            // ceea ce este foarte ineficient:
	            // (2xCall / Method) x useri simultan = n
	            // n call-uri la db
	            // Solutia ar fi ca getProductsByProjectId sa returneze un map<Integer, ?>
	            // si DBCall2 sa faci map.get(id)

            	putOnSession("currentProduct", currentProduct);
            }
            
            putOnState(ControllerConstants.NEXT_PAGE, "content/project/projectPage.jsp");
            putOnSession("currentTab", "tab3");
            
			break;
		
		}
		return null;
	}

}
